<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Customermodel extends CI_Model {

    protected $_CI;

    public static $searchField = array(
        'customer_id' => 'customer.customer_id',
        'customer_status' => 'customer.customer_status',
        'subscribe' => 'customer.subscribe',
        'sex' => 'customer.sex',
    );
    public static $likeField = array(
      'openid' => 'customer.openid',
      'nickname' => 'nickname',
      'city' => 'city',
      'province' => 'province',
      'country' => 'country',
      'customer_time_create_start' => 'customer_time_create >=',
      'customer_time_create_end' => 'customer_time_create <=',
      'customer_time_last_hb_start' => 'customer_time_last_hb >=',
      'customer_time_last_hb_end' => 'customer_time_last_hb <=',
      'openid' => 'openid',
      'history_wish' => 'history_wish',

    );
    public static $sortField = array(
      'customer_hb_times' => 'customer_hb_times',
    );

    public function __construct(){
        parent::__construct();
        $this->_CI = & get_instance();
    }
/*
| -------------------------------------------------------------------
|  GET Functions
| -------------------------------------------------------------------
*/
    public function getCustomerListSection($assist){
        if(isset($assist['select'])) $this->db->select($assist['select']);
        $this->db->from('customer');
        $this->db->where('customer_status !=',STATUS_DELETE);
        if(isset($assist['where'])) $this->db->where($assist['where']);
        if(isset($assist['like'])) $this->db->like($assist['like']);
        if (isset($assist['where_in']) && !empty($assist['where_in'])) {
            foreach ($assist['where_in'] as $k => $v) {
                if(!empty($v) && is_array($v)) $this->db->where_in($k,$v);
                else {
                    $query = $this->db->get();
                    if(isset($assist['nocount'])) return array();
                    return array(array(),0);
                }
            }
        }
        if(!isset($assist['nocount'])) $count = $this->db->count_all_results('',SQL_EXECUTE_RETAIN_CONDITION);

        // $this->db->order_by('customer_status','desc');
        // $this->db->order_by('customer_sort','desc');
        $this->db->order_by('customer_id','desc');
        if(isset($assist['pagination'])) $this->db->limit($assist['pagination']['limit'],$assist['pagination']['start']);
        $query = $this->db->get();
        $list = $query->result_array();

        if(isset($assist['nocount'])) return $list;
        return array($list,$count);
    }

    public function getHistoryListSection($assist){
      if(isset($assist['select'])) $this->db->select($assist['select']);
      $this->db->from('history');
      // $this->db->where('customer_status !=',STATUS_DELETE);
      if(isset($assist['join_customer'])) {
        $this->db->join('customer','customer.customer_id = history.customer_id','left');
      }
      if(isset($assist['join_user'])) {
        $this->db->join('user','user.user_id = history.user_id','left');
      }
      if(isset($assist['where'])) $this->db->where($assist['where']);
      if(isset($assist['like'])) $this->db->like($assist['like']);
      if (isset($assist['where_in']) && !empty($assist['where_in'])) {
          foreach ($assist['where_in'] as $k => $v) {
              if(!empty($v) && is_array($v)) $this->db->where_in($k,$v);
              else {
                  $query = $this->db->get();
                  if(isset($assist['nocount'])) return array();
                  return array(array(),0);
              }
          }
      }
      if(!isset($assist['nocount'])) $count = $this->db->count_all_results('',SQL_EXECUTE_RETAIN_CONDITION);

      $this->db->order_by('history_id','desc');
      if(isset($assist['pagination'])) $this->db->limit($assist['pagination']['limit'],$assist['pagination']['start']);
      $query = $this->db->get();
      $list = $query->result_array();

      if(isset($assist['nocount'])) return $list;
      return array($list,$count);
    }


    public function getCustomerSection($assist){
        if(isset($assist['select'])) $this->db->select($assist['select']);
        $this->db->from('customer');
        if(isset($assist['where'])) $this->db->where($assist['where']);
        if(isset($assist['like'])) $this->db->like($assist['like']);
        $this->db->limit(1);
        $query = $this->db->get();
        $res = $query->row_array();

        return $res;
    }

    public function getCustomer($customer_id){
        $this->db->from('customer');
        $this->db->where('customer_id',$customer_id);
        $this->db->limit(1);
        $query = $this->db->get();
        $res = $query->row_array();

        return $res;
    }

    public function getCustomerByOpenid($openid){
        $this->db->from('customer');
        $this->db->where('openid',$openid);
        $this->db->limit(1);
        $query = $this->db->get();
        $res = $query->row_array();

        return $res;
    }

    public function getCustomerById($customer_id){
        if(!is_array($customer_id)) $customer_id = array($customer_id);
        if(empty($customer_id)) return array();

        $this->db->from('customer');
        $this->db->where_in('customer_id',$customer_id);
        $query = $this->db->get();
        $list = $query->result_array();

        return $list;
    }

    public function getAllCustomer($select = '') {
      if(!empty($select)) $this->db->select($select);
      $this->db->from('customer');
      $this->db->where('customer_status !=',STATUS_DELETE);
      $query = $this->db->get();
      $list = $query->result_array();

      return $list;
    }

    public function getLastOpenid() {
      $this->db->from('customer');
      $this->db->order_by('customer_id','desc');
      $this->db->limit(1);
      $query = $this->db->get();
      $res = $query->row_array();

      return empty($res) ? '' : $res['openid'];
    }

/*
| -------------------------------------------------------------------
|  CREATE Functions
| -------------------------------------------------------------------
*/
    public function createCustomer($info){
      $db_debug = $this->db->db_debug;
      // $this->db->db_debug = FALSE;
      $m = $this->db->insert('customer',$info);
      $customer_id = $this->db->insert_id();
      $this->db->db_debug = $db_debug;

      return $m ? $customer_id : 0;
    }

    public function createHistory($info){
      $db_debug = $this->db->db_debug;
      // $this->db->db_debug = FALSE;
      $m = $this->db->insert('history',$info);
      $customer_id = $this->db->insert_id();
      $this->db->db_debug = $db_debug;

      return $m ? $customer_id : 0;
    }


    public function createCustomerBatch($data){
      if (!empty($data)) {
        $db_debug = $this->db->db_debug;
        // $this->db->db_debug = FALSE;
        $m = $this->db->insert_batch('customer',$data);
        $customer_id = $this->db->insert_id();
        $this->db->db_debug = $db_debug;

        return $m ? $customer_id : 0;
      }
      return 0;
    }

/*
| -------------------------------------------------------------------
|  EDIT Functions
| -------------------------------------------------------------------
*/
    public function editCustomer($info){
        if(isset($info['customer_id'])) {
            $customer_id = $info['customer_id'];
            unset($info['customer_id']);
            $this->db->where('customer_id',$customer_id);
            return $this->db->update('customer',$info);
        }
    }

    public function updateCustomerBatch($update_arr){
        if (!empty($update_arr)) {
            $this->db->update_batch('customer',$update_arr,'customer_id');
        }
    }

    public function updateCustomerHbData($customer_id) {
      $this->db->query('update {PRE}customer set customer_hb_times=(select count(*) from {PRE}history where {PRE}history.customer_id={PRE}customer.customer_id),
                          customer_time_last_hb=(select max(history_time_create) from {PRE}history where {PRE}history.customer_id={PRE}customer.customer_id) where customer_id='
                            .$customer_id);
    }

    public function sysnCustomerFromWx($update = false) {
      $this->load->library('rest');
      $customer_list = $this->getAllCustomer('customer_id,openid');
      $customer_list = reindexArray($customer_list,'openid');
      $token = file_get_contents(base_url('/symj/token/getAccessToken.php'));
      $openid_list = array();
      $total = 0;
      // $next_openid = $this->getLastOpenid();
      $next_openid = '';
      $update_openids = array();
      do {
        $result = json_decode(json_encode($this->rest->get('https://api.weixin.qq.com/cgi-bin/user/get?access_token='
            .$token.'&next_openid='.$next_openid)),true);
        // echo 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='
        //     .$token.'&next_openid='.$next_openid;
        if(empty($result['data'])) break;
        foreach ($result['data']['openid'] as $key => $openid) {
          if(!isset($customer_list[$openid])) {
            $openid_list[] = $openid;
          } else {
            $update_openids[] = $openid;
          }
        }
        $total = $result['total'];
        $next_openid = $result['next_openid'];
        // $openid_list = array_merge($openid_list,$result['data']['openid']);
      } while (count($openid_list) < $total);

      if($update) {
        $chunks = array_chunk($update_openids,100);
        $update_data = array();
        foreach ($chunks as $openids) {
          $params = array();
          foreach ($openids as $openid) {
            $params[] = array('openid' => $openid, 'lang' => 'zh_CN');
            // $result = json_decode(json_encode($this->rest->get('https://api.weixin.qq.com/cgi-bin/user/info'
            //           ,array('access_token' => $token,'openid' => $openid,'lang' => 'zh_CN'))),true);
          }
          $result = json_decode(json_encode($this->rest->post('https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token='.$token
                  ,json_encode(array('user_list' => $params)))),true);
          $update_data = array_merge($update_data,$result['user_info_list']);
        }
        $subscribe_data = array();
        $unsubscribe_data = array();
        foreach ($update_data as $key => $result) {
          if($result['subscribe'] == 1) {
            $result['tagid_list'] = json_encode($result['tagid_list'],JSON_UNESCAPED_UNICODE);
            $subscribe_data[] = $result;
          } else {
            $unsubscribe_data[] = $result;
          }
        }
        if(count($subscribe_data) > 0)
          $this->db->update_batch('customer',$subscribe_data,'openid');
        if(count($unsubscribe_data) > 0)
          $this->db->update_batch('customer',$unsubscribe_data,'openid');
      }

      if(empty($openid_list)) {
        $this->response->setSuccess(false);
        $this->response->setDetail('此次同步为0，未有新的粉丝');
        $this->response->responseExit();
      }

      $chunks = array_chunk($openid_list,100);
      $insert_data = array();
      foreach ($chunks as $openids) {
        $params = array();
        foreach ($openids as $openid) {
          $params[] = array('openid' => $openid, 'lang' => 'zh_CN');
          // $result = json_decode(json_encode($this->rest->get('https://api.weixin.qq.com/cgi-bin/user/info'
          //           ,array('access_token' => $token,'openid' => $openid,'lang' => 'zh_CN'))),true);
        }
        $result = json_decode(json_encode($this->rest->post('https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token='.$token
                ,json_encode(array('user_list' => $params)))),true);
        $insert_data = array_merge($insert_data,$result['user_info_list']);
      }

      foreach ($insert_data as $key => $result) {
        $insert_data[$key]['customer_time_subscribe'] = date('Y-m-d H:i:s',$result['subscribe_time']);
        $insert_data[$key]['tagid_list'] = json_encode($result['tagid_list'],JSON_UNESCAPED_UNICODE);
        $insert_data[$key]['customer_time_create'] = NOW;
      }
      $this->createCustomerBatch($insert_data);

      $this->response->setSuccess();
      $this->response->setDetail('导入粉丝数量['.count($insert_data).']成功!');
      $this->response->setAddon(array(
        'sql' => $this->db->last_query()
      ));
    	$this->response->responseExit();
    }

    function httpPost($url, $data) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }


    public function checkTemplateSend($customer_id,$template_id) {
      $this->db->from('history');
      $this->db->where('customer_id',$customer_id);
      $this->db->where('template_id',$template_id);
      $this->db->where('history_time_create >=',TODAY.' 00:00:00');
      $this->db->where('history_time_create <=',TODAY.' 23:59:59');
      $this->db->limit(1);
      $query = $this->db->get();
      $res = $query->row_array();

      return !empty($res);
    }
}
